import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/models/fund_record_list_entity.dart';

import '../../../constants.dart';
import '../../../theme.dart';
import 'logic.dart';

class FundRecordPage extends StatelessWidget {
  FundRecordPage({Key? key}) : super(key: key);

  final logic = Get.find<FundRecordLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('专款记录'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: _buildBg(children: [
        /// 流水列表
        _buildListBg(children: [
          Container(
            color: Colors.white,
            child: TabBar(
              controller: logic.tabController,
              tabs: logic.tabTitles.map((e) => Tab(text: e)).toList(),
            ),
          ),

          /// 分割线
          const Divider(),

          _buildListItemBg(builder: _itemBuilder),
        ]),

        _buildMoreTip(),

        SizedBox(height: kSpaceMedium),
      ]),
    );
  }

  Widget _buildListBg({required List<Widget> children}) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      decoration:
          BoxDecoration(borderRadius: BorderRadius.circular(kRadiusMedium)),
      child: Column(
        children: children,
      ),
    );
  }

  Widget _buildListItemBg({
    required List<Widget> Function(FundRecordListData item) builder,
  }) {
    return Obx(
      () => Column(
        children: List.generate(
          logic.fundRecords.length,
          (index) => Ink(
            color: Colors.white,
            child: InkWell(
              onTap: () => {logic.onClickRecord(logic.fundRecords[index])},
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: builder(logic.fundRecords[index]),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _itemBuilder(FundRecordListData item) {
    final typeInfo = fundRecordTypeMap[item.type] ?? fundRecordTypeMap[0]!;
    final desc = typeInfo.$1;
    final sign = typeInfo.$2;

    return [
      SizedBox(height: kSpaceSmall),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            desc,
            style: TextStyle(
              fontSize: kFontSizeMedium,
              color: AppColor.colorFontBlack,
            ),
          ),
          Text(
            '$sign${item.amount.replaceAll('¥', '')}',
            style: TextStyle(
              fontSize: kFontSizeMedium,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: kSpaceMini),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            item.createdAt == 0
                ? ''
                : DateFormat('yyyy-MM-dd HH:mm').format(
                    DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: Colors.grey,
            ),
          ),
          Text(
            '余额 ${item.totalBalance}',
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: Colors.grey,
            ),
          ),
        ],
      ),
      SizedBox(height: kSpaceMini),
      Text(
        item.remark ?? '',
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontSize: kFontSizeMini,
          color: Colors.grey,
        ),
      ),
      SizedBox(height: kSpaceSmall),
      const Divider(),
    ];
  }

  Widget _buildMoreTip() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Obx(
          () => Text(
            logic.bottomTips.value,
            style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
          ),
        ),
      ),
    );
  }

  Widget _buildBg({required List<Widget> children}) {
    return Obx(() {
      if (logic.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      } else {
        return RefreshIndicator(
          onRefresh: () async => logic.reload(),
          child: ListView(
            controller: logic.scrollController,
            children: children,
          ),
        );
      }
    });
  }
}
